import React from 'react';
import {Form, Input, Breadcrumb, Card, Cascader, Select, Modal, DatePicker , Table, Button, Col , InputNumber , message} from 'antd';
import ProductSearchModal from '../../product/components/ProductSearchModal'
import AppHelper from 'utils/AppHelper';

const { RangePicker } = DatePicker;
const productColumns = [{
  title: '商品名',
  dataIndex: 'name',
  key: 'name',
}, {
  title: '规格',
  dataIndex: 'spec',
  key: 'spec',
}, {
  title: '价格',
  dataIndex: 'age',
  key: 'age',
}, {
  title: '库存',
  dataIndex: 'address',
  key: 'address',
}, {
  title: '操作',
  dataIndex: 'operation',
  key: 'operation',
  render : function(){
    return (<div>删除</div>)
  }
}];


class ProductPromotionCreate extends React.Component {

    state = {
        type : 'P_DIS',
        searchProdVisible : false,
        selectedProducts : [],
        productSearchModalKey : 1
    }

    constructor(props){
        super(props)
        this.createUrl = AppHelper.config.serviceUrl + '/promotion/product'
    }


    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (err) {
                console.log('Received values of form: ', values);
                return ;
            }
            let formVals = this.props.form.getFieldsValue();
            formVals.productIdList = AppHelper.Arrays.pluck(this.state.selectedProducts , 'key');
            message.loading('保存中',0);
            fetch(this.createUrl , {
                method : 'POST',
                headers : {
                    'Accept' : 'application/json',
                    'Content-Type' : 'application/json'
                },
                body : JSON.stringify(formVals)
            }).then(res => res.json())
            .then((resp) => {
                message.destroy();
                console.info('success')
            })
            .catch((error) => {
                message.destroy();
            })
            console.info(formVals);
            console.info(this.state.selectedProducts)
        });
    }

    handleTypeChange = (type) => {
        this.setState({type});
    }

    showSearchProdModal = () =>{
        let modalKey = this.state.productSearchModalKey;
        this.setState({searchProdVisible : true , productSearchModalKey : modalKey +1})
    }

    handleSearchProdOk = (data) =>{
        let currentData = this.state.selectedProducts;
        let targetData = data.concat(currentData);
        this.setState({searchProdVisible : false , selectedProducts:targetData});

        
        
    }

    handleSearchProdCancel = () => {
        this.setState({searchProdVisible : false})
    }

    render() {
        const {getFieldDecorator} = this.props.form;

        const formItemLayout = {
            labelCol: {
                xs: {span: 20},
                sm: {span: 3},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 14},
            },
        };
        const tailFormItemLayout = {
            wrapperCol: {
                xs: {
                    span: 24,
                    offset: 0,
                },
                sm: {
                    span: 14,
                    offset: 6,
                },
            },
        };
        return (
            <div>
                <Breadcrumb className="App-breadcrumb">
                    <Breadcrumb.Item>首页</Breadcrumb.Item>
                    <Breadcrumb.Item>促销管理</Breadcrumb.Item>
                    <Breadcrumb.Item>创建商品促销</Breadcrumb.Item>
                </Breadcrumb>
                <Card bordered={false}>
                    <Form onSubmit={e => {this.handleSubmit(e)}}>
                        <Form.Item {...formItemLayout} label="活动名称" hasFeedback >
                            {getFieldDecorator('name', {
                                rules: [{required: true, message: '请填写活动名称!', whitespace: true}],
                            })(
                                <Input/>
                            )}
                        </Form.Item>
                        <Form.Item {...formItemLayout} label="活动类型" hasFeedback >
                            {getFieldDecorator('type', {
                                initialValue: 'P_DIS',
                                rules: [{required: true, message: '请选择活动类型!'}],
                            })(
                                <Select onChange={this.handleTypeChange}>
                                    <Select.Option value="P_DIS">打折</Select.Option>
                                    <Select.Option value="P_DP">减价</Select.Option>
                                    <Select.Option value="P_FP">固定价格出售</Select.Option>
                                    <Select.Option value="P_EPR">满额减</Select.Option>
                                    <Select.Option value="P_EAR">满件减</Select.Option>
                                </Select>
                            )}
                        </Form.Item>
                        {
                            this.state.type == 'P_DIS'
                            &&
                            <Form.Item {...formItemLayout} label="折扣" hasFeedback >
                                {getFieldDecorator('discount', {
                                    rules: [{required: true, message: '请填写折扣!'}],
                                })(
                                    <InputNumber style={{width:'auto'}}
                                                 min={0}
                                                 max={100}
                                                 formatter={value => `${value}%`}
                                                 parser={value => value.replace('%', '')}/>
                                )}
                            </Form.Item>
                        }
                        {
                            this.state.type == 'P_DP'
                            &&
                            <Form.Item {...formItemLayout} label="立减金额" hasFeedback >
                                {getFieldDecorator('deduction', {
                                    rules: [{required: true, message: '请填写立减金额!'}],
                                })(
                                    <InputNumber style={{width:'auto'}}/>
                                )}
                            </Form.Item>
                        }
                        {
                            this.state.type == 'P_FP'
                            &&
                            <Form.Item {...formItemLayout} label="固定价格" hasFeedback >
                                {getFieldDecorator('fixedPrice', {
                                    rules: [{required: true, message: '请填写固定价格!'}],
                                })(
                                    <InputNumber style={{width:'auto'}}/>
                                )}
                            </Form.Item>
                        }
                        {
                            this.state.type == 'P_EPR'
                            &&
                            <Form.Item {...formItemLayout} label="满额减" hasFeedback >
                                {getFieldDecorator('fixedPrice', {
                                    rules: [{required: true, message: '请填写固定价格!'}],
                                })(
                                    <InputNumber style={{width:'auto'}}/>
                                )}
                            </Form.Item>
                        }
                        {
                            this.state.type == 'P_EAR'
                            &&
                            <Form.Item {...formItemLayout} label="满件减" hasFeedback >
                                {getFieldDecorator('fixedPrice', {
                                    rules: [{required: true, message: '请填写固定价格!'}],
                                })(
                                    <InputNumber style={{width:'auto'}}/>
                                )}
                            </Form.Item>
                        }
                        <Form.Item {...formItemLayout} label="活动期限" hasFeedback>
                            <Col span={5}>
                            <Form.Item>
                                {getFieldDecorator('startTime',{
                                    rules: [{required: true}],
                                })(
                                    <DatePicker
                                      showTime
                                      format="YYYY-MM-DD HH:mm:ss"
                                      placeholder="开始日期"
                                    />
                                )}
                            </Form.Item>
                          </Col>
                          <Col span={2}>
                            <p className="ant-form-split">-</p>
                          </Col>
                          <Col span={4}>
                            <Form.Item>
                                {getFieldDecorator('endTime',{
                                    rules: [{required: true, message: ''}],
                                })(
                                    <DatePicker
                                      showTime
                                      format="YYYY-MM-DD HH:mm:ss"
                                      placeholder="结束日期"
                                    />
                                )}
                            </Form.Item>
                          </Col>
                        </Form.Item>
                        <Form.Item {...formItemLayout} label="选择活动商品" hasFeedback >
                            <Button type="primary" onClick={this.showSearchProdModal}>选择商品</Button>
                            <ProductSearchModal key={this.state.productSearchModalKey} 
                                                visible={this.state.searchProdVisible} 
                                                onOk={this.handleSearchProdOk} 
                                                onCancel={this.handleSearchProdCancel}/>
                        </Form.Item>
                        <Form.Item {...formItemLayout} label="已选择的商品" hasFeedback >
                            <Table pagination={false} size='small' dataSource={this.state.selectedProducts} columns={productColumns} />
                        </Form.Item>
                        <Form.Item {...tailFormItemLayout}>
                            <Button type="primary" htmlType="submit" size="large">添加属性</Button>
                        </Form.Item>
                    </Form>
                </Card>
            </div>
        );
    }
}

const ProductPromotionCreatePage = Form.create()(ProductPromotionCreate);

export default ProductPromotionCreatePage;